<template>
  <el-dropdown trigger="click" class="dingtalk-language-switcher" @command="handleSetLanguage">
    <div class="language-trigger">
      <span class="current-language">
        {{ currentLanguage.label }}
      </span>
      <i class="el-icon-arrow-down"></i>
    </div>
    <el-dropdown-menu slot="dropdown" class="language-menu">
      <el-dropdown-item v-for="lang in languages" :key="lang.value" :command="lang.value" :class="{ 'active': language === lang.value }">
        {{ lang.label }}
      </el-dropdown-item>
    </el-dropdown-menu>
  </el-dropdown>
</template>

<script>
  import {
    changeLanguage
  } from "@/api/login";

  export default {
    data() {
      return {
        languages: [
          { value: 'zh_CN', label: '简体中文' },
          { value: 'en_US', label: 'English' }
          // 可以继续添加其他语言
        ]
      }
    },
    computed: {
      language() {
        return this.$store.getters.language || 'zh_CN';
      },
      currentLanguage() {
        return this.languages.find(lang => lang.value === this.language) || this.languages[0];
      }
    },
    methods: {
      handleSetLanguage(lang) {
        if (this.language === lang) {
          return;
        }
        this.$i18n.locale = lang;
        this.$store.dispatch('app/setLanguage', lang);
        changeLanguage(lang).then(() => {
          this.$message.success(this.$t('登录_切换语言成功'));
        }).catch(() => {
          this.$message.error(this.$t('登录_切换语言失败'));
        });
      }
    }
  }
</script>

<style lang="scss" scoped>
.dingtalk-language-switcher {
  cursor: pointer;
  margin: 0 10px;
  font-size: 14px;
  color: #333;

  .language-trigger {
    display: flex;
    align-items: center;
    padding: 0 5px;
    height: 100%;

    .current-language {
      margin-right: 4px;
    }

    .el-icon-arrow-down {
      font-size: 12px;
      color: #999;
      transition: transform 0.3s;
    }
  }

  &:hover {
    color: var(--el-color-primary);

    .el-icon-arrow-down {
      color: var(--el-color-primary);
    }
  }

  // 下拉菜单展开时箭头旋转
  &.is-active {
    .el-icon-arrow-down {
      transform: rotate(180deg);
    }
  }
}

.language-menu {
  min-width: 160px;
  padding: 5px 0;

  .el-dropdown-menu__item {
    padding: 0 16px;
    line-height: 36px;
    font-size: 14px;

    &:hover {
      color: var(--el-color-primary);
      background-color: #f5f5f5;
    }

    &.active {
      color: var(--el-color-primary);
      background-color: #f0f7ff;
    }
  }
}
</style>
